package com.example.demo.controller;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("excelDemo")
public class ExcelDemo {
    @RequestMapping("test")
    public String test() {
        return "666";
    }

    @RequestMapping("excel03ReadTest")
    public String excel03ReadTest(@RequestBody MultipartFile file) throws IOException {
        if (file == null)
            return "没读到文件";
        String originalFilename = file.getOriginalFilename();
        // 取出excel文件信息
        InputStream inputStream = file.getInputStream();
        Workbook workbook = new HSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Row rowTitle = sheet.getRow(0);
        if (rowTitle != null) {
            for (int cellNum = 0; cellNum < rowTitle.getPhysicalNumberOfCells(); cellNum++) {
                Cell cell = rowTitle.getCell(cellNum);
                if (cell != null) {
                    // int cellType = cell.getCellType();
                    CellType cellType = cell.getCellType();
                    System.out.println(cellType + ":" + cell.getStringCellValue());
                }
            }
        }
        inputStream.close();
        return originalFilename;
    }

    @RequestMapping("excel07ReadTest")
    public String excel07ReadTest(@RequestBody MultipartFile file) throws IOException {
        if (file == null)
            return "没读到文件";
        String originalFilename = file.getOriginalFilename();
        // 取出excel文件信息
        InputStream inputStream = file.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Row rowTitle = sheet.getRow(0);
        if (rowTitle != null) {
            for (int cellNum = 0; cellNum < rowTitle.getPhysicalNumberOfCells(); cellNum++) {
                Cell cell = rowTitle.getCell(cellNum);
                if (cell != null) {
                    CellType cellType = cell.getCellType();
                    System.out.println(cellType + ":" + cell.getStringCellValue());
                }
            }
        }
        inputStream.close();
        return originalFilename;
    }
}
